/* eslint-disable @typescript-eslint/no-unused-vars */
import type {AxiosRequestTransformer,AxiosError} from 'axios'
import axios from 'axios'
import config from '@/config.json'
import qs from 'qs'
import {message} from 'antd'
import useAppStore from '@/store/app-store'
import { resetAllStore } from '@/store/resetter'
const instance = axios.create ({
    baseURL:config.baseURL,
    headers:{
        'Content-Type':'application/x-www-form-urlencoded',
        'x-api-key':'ab428ee8-c6ae-4bee-86ca-a5bd3437cff5'
    }
})

//响应拦截器
instance.interceptors.response.use(

  function (response){
   //有响应体的情况
  if (response.data){

    return response.data
  } else {
    //自定义响应体
    return {code:0,message:response.statusText}
  }
  return response
},
function (error:AxiosError<{code:number;message:string}>){

  if(error.response && error.response.data){
    //有响应体
    if(error.response.status ===401){
      //token过期
      useAppStore.getState().token && message.error('登录过期，请重新登录')
      //清空
      useAppStore.getState().token && resetAllStore()
      //跳转到登录页
      
    } else{
      message.error(error.response.status)
    }
      message.error(error.response.data.message)
      return Promise.reject(error.response.data);
  } else{
    //没有响应体
    console.log(error)
    let msg = ''
    switch(error.code){
       case 'ERR_NETWORK':
          msg = '网络似乎断开..'
          break
       case 'ECONNAVORTED':
          msg = '请求超时'
          break
       default:
           msg = error.message
    }
    message.error(msg)
    return Promise.reject({code:1,message:error.message})
  }
})


//请求拦截器
instance.interceptors.request.use(

    function (config) {
      const url = config.url
      const method = config.method?.toUpperCase()
    //为config挂载请求体转换器
    if ((url ==='/my/article/add' && method === 'POST' )|| (url ==='/my/article/info' && method === 'PUT')) {
      config.transformRequest = []
    } else {
      config.transformRequest = requestTransformer 
    }

    //为请求头按需挂载 token
    const token =useAppStore.getState().token
    if(url?.includes('/my') && token){
      config.headers.Authorization =token
    }
    return config

  }, function (error) {
    // Do something with request error
    return Promise.reject(error)
  });


//请求体转换器函数
const requestTransformer:AxiosRequestTransformer = (data) =>{
    if(data instanceof FormData){
      return qs.stringify(Object.fromEntries(data))
    } else {
      return qs.stringify(data)  
    }
}
 
  
export default instance